import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:xws/utils/theme_util.dart';

import 'back_icon.dart';

/// 安全应用栏
class SafeAppBar extends StatelessWidget implements PreferredSizeWidget {
  const SafeAppBar({
    Key? key,
    this.title,
    this.titleText,
    this.leading,
    this.actions,
    this.autoBackIcon = true,
    this.padding = const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
    this.titleTextStyle,
    this.bgDecoration,
    this.appBarColor,
    this.withStatusBarHeight = true,
    this.centerTitle = true,
    this.titlePadding = const EdgeInsets.symmetric(horizontal: 50),
  }) : super(key: key);

  final Widget? title;

  final String? titleText;

  final Widget? leading;

  final List<Widget>? actions;

  final bool autoBackIcon;

  final EdgeInsets padding;

  final EdgeInsets titlePadding;

  final TextStyle? titleTextStyle;

  final Decoration? bgDecoration;

  final Color? appBarColor;

  final bool withStatusBarHeight;

  final bool centerTitle;

  @override
  Widget build(BuildContext context) {
    return Container(
      width: sw,
      height: kToolbarHeight + (withStatusBarHeight ? statusBarHeight : 0),
      padding: EdgeInsets.only(
        top: (withStatusBarHeight ? statusBarHeight : 0) + padding.top,
        left: padding.left,
        right: padding.right,
        bottom: padding.bottom,
      ),
      color: appBarColor ?? th(context).bottomAppBarColor,
      decoration: bgDecoration,
      child: Stack(
        fit: StackFit.expand,
        alignment: Alignment.center,
        children: <Widget>[
          _title(context),
          _leading,
          _actions,
        ],
      ),
    );
  }

  /// 构建leading
  Widget get _leading {
    Widget? l = leading;

    if (leading == null && autoBackIcon) {
      l = const BackIcon();
    }

    if (l == null) return const SizedBox.shrink();

    return Positioned(
      left: 0,
      top: 0,
      bottom: 0,
      child: l,
    );
  }

  /// 构建title
  Widget _title(BuildContext context) {
    Widget titleWidget = Padding(
      padding: titlePadding,
      child: DefaultTextStyle(
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: th(context).textTheme.headline6!.copyWith(
              fontWeight: titleTextStyle?.fontWeight ?? FontWeight.bold,
              fontSize: titleTextStyle?.fontSize,
              color: titleTextStyle?.color,
            ),
        child: title ?? Text(titleText ?? ''),
      ),
    );

    if (centerTitle) titleWidget = Center(child: titleWidget);

    return titleWidget;
  }

  /// 构建actions
  Widget get _actions {
    if (actions == null || actions!.isEmpty) return const SizedBox.shrink();

    return Positioned(
      right: 0,
      top: 0,
      bottom: 0,
      child: Row(children: actions!),
    );
  }

  @override
  Size get preferredSize => Size(
        sw,
        kToolbarHeight + (withStatusBarHeight ? statusBarHeight : 0),
      );
}
